package com.amos.mqserver.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * @ClassName: RabbitMQConfig
 * @Description: rabbitMQ配置类
 * @author: amos
 * @date: 2018年8月21日 下午4:36:03
 */
@Configuration
//@Order(10)
public class RabbitMQConfig {

	private static final Logger logger = LoggerFactory.getLogger(RabbitMQConfig.class);

    /**
     * RabbitMQ连接信息
     */
    @Value("${spring.rabbitmq.host:10.3.98.163}")
    private String host;
    @Value("${spring.rabbitmq.port:5670}")
    private String port;
    @Value("${spring.rabbitmq.username:admin}")
    private String username;
    @Value("${spring.rabbitmq.password:123456}")
    private String password;
    @Value("${spring.rabbitmq.virtual-host:/}")
    private String virtualHost;
    @Value("${spring.rabbitmq.publisher-confirms:true}")
    private boolean publisherConfirms;

    /**
     * 注入RabbitMQ连接
     * @return ConnectionFactory
     */
    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses(host+":"+port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(virtualHost);
        /** 如果要进行消息回调，则这里必须要设置为true */
        connectionFactory.setPublisherConfirms(publisherConfirms);
        connectionFactory.setPublisherReturns(true);
        connectionFactory.setChannelCacheSize(100);
        return connectionFactory;
    }

    /**
     * 因为要设置回调类，所以应是prototype类型，如果是singleton类型，则回调类为最后一次设置
     */
    @Bean(name = "rabbitT")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        template.setMessageConverter(new Jackson2JsonMessageConverter());
        return template;
    }

    /**
     * RabbitAdmin封装了一些管理操作
     * @param connectionFactory
     * @return
     */
    @Bean
    RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        return new RabbitAdmin(connectionFactory);
    }
}
